package com.bear.richtext.type

import android.content.Context
import android.content.Intent
import android.graphics.Paint
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.FrameLayout
import androidx.core.view.setMargins
import com.bear.richtext.Constant
import com.bear.richtext.R
import com.bear.richtext.utils.Tools
import org.json.JSONObject

/**
 * 可点击文本，适合超链接
 */
class ItemClickable() : RichItem() {

    companion object {
        const val URL = "url" //超链接
        const val TEXT = "text" //显示的文本
        const val TAG = "ItemClickable"
    }

    private var url: String? = null
    private var text: String? = null

    constructor(context: Context, jsonObject: JSONObject) : this() {
        this.richView = parse(context, jsonObject)
    }

    override fun toJson(): JSONObject {
        (this.richView)?.let {
            var jsonObject = JSONObject()
            jsonObject.put(TYPE, RichItemType.Clickable)
            var attrs = JSONObject()
            attrs.put(URL, url)
            attrs.put(TEXT, text)
            jsonObject.put(ATTRS, attrs)
            return jsonObject
        }
        return JSONObject()
    }

    override fun parse(context: Context, jsonObject: JSONObject): View {
        try {
            this.url = jsonObject.optJSONObject(ATTRS).optString(URL)
            this.text = jsonObject.optJSONObject(ATTRS).optString(TEXT)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        val clickable = EditText(context)
        val layoutParams = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT
        )
        layoutParams.setMargins(Constant.Default_MARGIN)
        clickable.layoutParams = layoutParams
        clickable.isCursorVisible = true
        clickable.background = null
        clickable.paint.flags = Paint.UNDERLINE_TEXT_FLAG
        clickable.setText(text)
        clickable.setOnClickListener {
            this.url?.let {
                try {
                    val uri = Uri.parse(url)
                    val intent = Intent(Intent.ACTION_VIEW, uri)
                    context.startActivity(intent)
                } catch (e: Exception) {
                    Tools.elog(TAG, "click error:${e}")
                }
            }
        }
        return clickable
    }

    override fun type(): RichItemType {
        return RichItemType.Clickable
    }

    override fun setEditable(editable: Boolean) {
        super.setEditable(editable)
        this.richView?.apply {
            if (!editable) {
                this.setFocusable(false)
                this.isFocusableInTouchMode = false
            } else {
                this.setFocusable(true)
                this.isFocusableInTouchMode = true
            }
        }
    }
}